package ua.pp.bizon.yandex.uploader.remote;

import ua.pp.bizon.yandex.api.IHTTPUtils;
import ua.pp.bizon.yandex.api.ObjectLookup;
import ua.pp.bizon.yandex.uploader.atom.EntryAlbum;
import ua.pp.bizon.yandex.uploader.atom.Photo;

import java.io.File;
import java.io.StringReader;

import org.apache.abdera.model.Document;
import org.apache.abdera.model.Element;
import org.apache.abdera.parser.stax.FOMParserFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpException;
import org.apache.http.entity.FileEntity;
import org.apache.http.message.BasicHeader;

public class RemotePhotoCreator {

	private static Log log = LogFactory.getLog(RemotePhotoCreator.class);

	public Photo upload(File file, EntryAlbum to) throws HttpException {
		log.debug("start upload file " + file + " to " + to.getLink(EntryAlbum.SELF));
		FileEntity fileEntity = new FileEntity(file, "image/jpeg");
		Header[] headers = new Header[1];
		headers[0] = new BasicHeader("Slug", file.getName());
		Document<Element> document = null;
		String result = null;
		try {
			result = ObjectLookup.lookup(IHTTPUtils.class).post(fileEntity, to.getPhotosLink(), "image/jpeg", headers);
		} catch (HttpException e) {
			log.warn(e.getMessage(), e);
			throw e;
		}
		log.debug("uploaded " + file);
		document = new FOMParserFactory().getParser().parse(new StringReader(result));
		Photo photo = new Photo(document.getRoot());
		for (int i = 0; i < 3; i++) {
			try {
				photo.setName(file.getName());
				break;
			} catch (HttpException e) {
				log.warn("photo is not renamed, cause: " + e.getMessage(), e);
			}
		}
		return photo;
	}

	public Photo update(Photo photo) throws HttpException {
		log.debug("start update photo " + photo.getID());
		log.trace("photo entry: " + photo);
		String text = photo.getElement().toString();
		String res = null;
		try {
			res = ObjectLookup.lookup(IHTTPUtils.class).put(text, photo.getLink("edit"));
		} catch (HttpException e) {
			log.warn(e.getMessage());
			throw e;
		}
		Document<Element> document = null;
		document = new FOMParserFactory().getParser().parse(new StringReader(res));
		photo = new Photo(document.getRoot());
		return photo;
	}
}
